<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $permissions = array(
			'add_user' => array('admin','manag'),
			'index' => array('admin','manag'),
			'view' => array('admin','manag','users'),
			'edit' => array('admin','manag'),
			'delete' => array('admin','manag')
	);
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->autoRedirect = false;
		if(!empty($this->data) && isset($this->data['User']['email']) && is_numeric($this->data['User']['email'])){
			$this->data['User']['id'] = $this->data['User']['email'];
			$this->Auth->fields = array('username' => 'id', 'password' => 'password');
		}else{
			$this->Auth->fields = array('username' => 'email', 'password' => 'password');
		}
	}
	
	public function beforeRender(){
		parent::beforeRender();
	}
	
	function login(){
		if(!empty($this->data)){
			$this->Auth->login($this->data);
			if($this->Session->check('Auth.User.id')){
				$user = $this->User->findById($this->Auth->user('id'));
				$this->Session->write("User",$user);
				
				switch($this->Session->read('Auth.User.group')){
					case 'admin':
						$this->Auth->loginRedirect = array('plugin'=>null,'controller' => 'users', 'action' => 'index');
						break;
					case 'manag':
						$this->Auth->loginRedirect = array('plugin'=>null,'controller' => 'users', 'action' => 'index');
						break;
					case 'users':
						$this->Auth->loginRedirect = array('plugin'=>null,'controller' => 'pages', 'action' => 'index');
						break;
				}
				
				$this->redirect($this->Auth->loginRedirect);
			}else{
				$this->Session->setFlash(__('The user could not login. Please, try again.', true));
			}
		}
	}
	
	function logout() {
		$this->Session->delete("User");
		$this->Session->delete("Auth");
		$this->Session->delete('Store');
		$this->Session->delete('Timeline',array());
	
		$this->Session->setFlash(__('You have been successfully logged out.', true));
		$this->redirect($this->Auth->logout());
	}
	
	function index() {
		$this->User->recursive = 0;

		$this->set('users', $this->User->find('all',array('conditions'=>array('User.group'=>'users'))));		
		$this->set('providers', $this->User->find('all',array('conditions'=>array('User.group'=>'manag'))));
	}

	function view($id = null) {
	
		if($id != null && $id != $this->Auth->user('id') && $this->Auth->user('group') != 'admin'){
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect('/');
		}
		
		$id = (is_null($id)) ? $this->Auth->user('id') : $id;

		if (!empty($this->data)) {
    		$this->transaction->begin($this);
			if(isset($this->data['User']['new_password']) && isset($this->data['User']['old_password']) && !empty($this->data['User']['new_password']) && !empty($this->data['User']['old_password'])){		
				$current_password = $this->User->field('password',array('User.id'=>$id));
				if($current_password == $this->Auth->password($this->data['User']['old_password'])){
					
					$new_password = $this->Auth->password($this->data['User']['new_password']);
					$this->data['User']['password'] =  $new_password;

				}else{
					$this->Session->setFlash(__('Unfortunately there is a problem and your new informations could not be saved. Please contact our team.', true));
					return;	
				}
			}
			
			if(isset($this->data['User']['email_password']) && !empty($this->data['User']['new_email']) && !empty($this->data['User']['new_email'])){
				$current_password = $this->User->field('password',array('User.id'=>$id));
				if($current_password == $this->Auth->password($this->data['User']['email_password'])){
					$this->data['User']['old_email'] =  $this->data['User']['email']; // save old e-mail
					$this->data['User']['email'] =  $this->data['User']['new_email'];			
				}else{
					$this->Session->setFlash(__('Unfortunately there is a problem and your new informations could not be saved. Please contact our team.', true));
					return;
				}
			}
						

			$this->User->set( $this->data );
			if ($this->User->validates()){
				if ($this->User->save($this->data)){
					
					$this->transaction->commit($this);
    				$this->Session->setFlash(__('The new data has been updated. Thank you.', true));
    				
				} else {
					$this->Session->setFlash(__('Unfortunately there is a problem and your new informations could not be saved. Please contact our team.', true));
					$this->transaction->rollback($this);
				}	
			} else {
				$this->Session->setFlash(__('Unfortunately there is a problem and your new informations could not be saved. Please contact our team.', true));
				$this->transaction->rollback($this);
			}
		}
		
		if (empty($this->data)) {
			$this->User->recursive = 2;
			$this->data = $this->User->read(null, $id);
// 			debug($this->data);
		}
	}

	function add_user() {
		if (!empty($this->data)) {
			$this->data['User']['group'] = 'users';
			
			$this->User->set( $this->data );
			if ($this->User->validates()) {
				if($this->data['User']['password'] ==  $this->Auth->password( $this->data['User']['repeat_password'])){
				
					$this->User->create();
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('The user has been saved', true));
						$this->redirect(array('action' => 'index'));
					} else {
						$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
					}
				}else{
					$this->Session->setFlash(__('The user could not be saved. Please enter the correct password.', true));
				}
			}else{
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
			$this->data['User']['password'] = '';
		}
	}

	function add_provider() {
		if (!empty($this->data)) {
				
			$this->data['User']['group'] = 'manag';
				
			$this->User->set( $this->data );
			if ($this->User->validates()) {
				if($this->data['User']['password'] ==  $this->Auth->password( $this->data['User']['repeat_password'])){
	
					$this->User->create();
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('The user has been saved', true));
						$this->redirect(array('action' => 'index#tabs-providers'));
					} else {
						$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
					}
				}else{
					$this->Session->setFlash(__('The user could not be saved. Please enter the correct password.', true));
				}
			}else{
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
	}
	
	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The user has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for user', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->delete($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('User was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	function register() {
		if (!empty($this->data)) {
			$this->data['User']['group'] = 'users';
			$this->data['User']['created'] = date('Y-m-d H:i:s');
			$this->User->set( $this->data );
			if ($this->User->validates()) {
				if($this->data['User']['password'] ==  $this->Auth->password( $this->data['User']['repeat_password'])){
	
					$this->User->create();
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('Rejestracja zakończona pomyslnie. Dziękujemy.', true));
	
						if($this->Auth->login($this->data)){
							$this->redirect('/');
						}
						
						$this->Email->to = 'kowal.sylwester@gmail.com';
// 						$this->Email->bcc = array('bok@21w.pl');
						$this->Email->subject = 'Nowy email z '. $_SERVER['HTTP_HOST'];
						$this->Email->replyTo = $this->data['User']['email'];
						$this->Email->from = $_SERVER['HTTP_HOST']." <{$this->data['User']['email']}>";
						$this->Email->template = false;
						$this->Email->sendAs = 'text'; // text; html; both;
						$this->Email->send();
	
					} else {
						$this->Session->setFlash(__('Rejestracja nie powiodła się. Prosimy ja ponowić', true));
					}
				}else{
					$this->Session->setFlash(__('Rejestracja nie powiodła się. Prosimy o podanie poprawnie pól z hasłem', true));
				}
			}else{
				$this->Session->setFlash(__('Rejestracja nie powiodła się. Prosimy ja ponowić.', true));
			}
			$this->data['User']['password'] = '';
		}
	}

	public function new_password(){
	
		if(!empty($this->data) && isset($this->data['User']['email'])){
			$user = $this->User->findByEmail($this->data['User']['email']);
			if(!is_array($user)){
				$this->Session->setFlash(__("You have entered the wrong address e-mial",true));
				$this->redirect($this->referer());
			}
			$new_password = $this->Password->get();
			$user['User']['password'] = $this->Auth->password($new_password);
			$this->User->id = $user['User']['id'];
			if($this->User->save($user)){
				$user['User']['password'] = $new_password;
				$this->data = $user;
				$this->Email->to = $user['User']['email'];
				$this->Email->bcc = array('bok@21w.pl');
				$this->Email->subject = __("New SnapCuts password.",true);
				$this->Email->replyTo = $user['User']['email'];
				$this->Email->from = $_SERVER['HTTP_HOST'].' <info@snapcuts.com>';
				$this->Email->template = 'new-password';
				$this->Email->sendAs = 'both'; // text; html; both;
	
				if ( $this->Email->send() ) {
					$this->Session->setFlash(__("Password has been reset. Please check your email.",true));
				} else {
					$this->Session->setFlash(__("Error sending. Please, try again.",true));
				}
				$this->redirect($this->referer());
			}
		}
	}
}
